<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form class="permission-form" :form="form">
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="唯一标识" v-show="xsFlag" hasFeedback>
        <a-input v-decorator="['id']" :disabled="true" />
      </a-form-item>
      <!--   <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务名称" hasFeedback>
        <a-input
          placeholder="起一个服务名称"
          autocomplete="flName"
          v-decorator="['flName', { rules: [{ required: true, message: '用户名不能为空' }] }]"
        />
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="昵称" hasFeedback>
        <a-input placeholder="起一个昵称" v-decorator="['nickname']" autocomplete="nickname" />
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" v-show="!xsFlag" hasFeedback> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码" hasFeedback>
        <a-input-password
          placeholder="密码"
          autocomplete="current-password"
          v-decorator="['password', { rules: [{ required: true, message: '密码不能为空' }] }]"
        />
      </a-form-item> -->

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="性别" hasFeedback validateStatus="success">
        <a-select v-decorator="['sex', { initialValue: 0 }]">
          <a-select-option :value="0">男</a-select-option>
          <a-select-option :value="1">女</a-select-option>
          <a-select-option :value="2">未知</a-select-option>
        </a-select>
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所属类型" hasFeedback validateStatus="success">
        <a-select @change="gbChange" v-decorator="['type', { initialValue: 0 }]">
          <a-select-option :value="0">父级</a-select-option>
          <a-select-option :value="1">子级</a-select-option>
        </a-select>
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态" hasFeedback validateStatus="success">
        <a-select v-decorator="['status', { initialValue: 0 }]">
          <a-select-option :value="0">启用</a-select-option>
          <a-select-option :value="1">禁用</a-select-option>
        </a-select>
      </a-form-item> -->

      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="邮箱" hasFeedback>
        <a-input
          :rows="5"
          placeholder="请输入邮箱"
          v-decorator="[
            'email',
            {
              rules: [
                { required: true, message: '邮箱不能为空' },
                { type: 'email', message: '请输入正确的邮箱格式' }
              ]
            }
          ]"
        />
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="github账号" hasFeedback>
        <a-input :rows="5" placeholder="请输入github账号名字" v-decorator="['githubLogin']" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="gitee账号" hasFeedback>
        <a-input :rows="5" placeholder="请输入gitee账号名字" v-decorator="['giteeLogin']" />
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="电话" hasFeedback>
        <a-input
          :rows="5"
          placeholder="请输入电话"
          v-decorator="[
            'phone',
            {
              rules: [
                { required: true, message: '电话不能为空' },
                { pattern: new RegExp(/^1[3-9]\d{9}$/), message: '电话格式不对' }
              ]
            }
          ]"
        />
      </a-form-item> -->
      <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="服务图片" hasFeedback>
        <a-upload
          :customRequest="uploadimage"
          list-type="picture-card"
          :file-list="fileList"
          @preview="handlePreview"
          @change="handleChange"
          :remove="removeFile"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus" />
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleC">
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item> -->
      <!-- <a-divider>拥有角色</a-divider> -->

      <a-form-item
        v-show="typed != 0"
        label="服务分类父级"
        name="actions"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        hasFeedback
      >
        <a-select
          show-search
          style="width: 100%"
          :filter-option="filterOption"
          v-decorator="['serviceid']"
          :allowClear="true"
        >
          <a-select-option v-for="(action, index) in RolesLists" :key="index" :value="action.value">
            {{ action.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="服务详情" name="actions2" :labelCol="labelCol" :wrapperCol="wrapperCol" hasFeedback>
        <a-select
          show-search
          style="width: 100%"
          :filter-option="filterOption"
          v-decorator="['detailid']"
          :allowClear="true"
        >
          <a-select-option v-for="(action, index) in RolesLists2" :key="index" :value="action.value">
            {{ action.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
// import { decryptStr } from '@/utils/passwordUtils'
// import { getPermissions } from '@/api/manage'
// import pick from 'lodash.pick'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
export default {
  name: 'RoleModal',
  data() {
    return {
      typed: 1,
      RolesLists: [],
      RolesLists2: [],
      xsFlag: false,
      title: '新增角色',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      // mdl: {
      //   actions: [] // 初始化为默认选中的值
      // },

      form: this.$form.createForm(this),
      permissions: [],
      previewVisible: false,
      previewImage: '',
      fileList2: [],
      fileList: [
        /* {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-2',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-3',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-4',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        },
        {
          uid: '-5',
          name: 'image.png',
          status: 'error'
        } */
      ]
    }
  },
  created() {
    this.loadPermissions()
    this.loadPermissions2()
  },
  mounted() {
    // console.log('mounted')
  },
  methods: {
    gbChange(e) {
      console.log('改变', e)
      this.typed = e
    },
    filterOption(input, option) {
      // console.log('input', input)
      // console.log('option', option)

      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    removeFile(e) {
      console.log('删除文件', e.name)
      // this.$http.post('/common/del', { filename: e.name }).then((res) => {
      //   console.log(res)
      // })
      this.fileList = []
    },
    uploadimage(file, fileList) {
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file) // 'file' 是文件的表单字段名，file 是文件对象
      this.$http
        .post('/serviceClassification/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data' // 确保请求头设置为 multipart/form-data
          }
        })
        .then((res) => {
          console.log('上传成功', res)
          this.fileList = res.result
        })
      // console.log(this.fileList)
    },
    handleC() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    filterByValue(arr, valueArray) {
      return arr.filter((item) => valueArray.includes(item.value))
    },
    // 验证状态的动态显示
    validateStatus(fieldName) {
      const { getFieldError, isFieldTouched } = this.form
      if (isFieldTouched(fieldName) && getFieldError(fieldName)) {
        return 'error'
      }
      return 'success'
    },
    add() {
      console.log('add')

      this.visible = true
      this.xsFlag = false
      this.title = '新增服务与详情绑定'
      this.fileList = []
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.setFieldsValue({
            id: '',
            serviceid: '',
            detailid: ''
          })
        })
      })

      this.loadPermissions()
      this.loadPermissions2()
    },
    watch(record) {
      console.log('watch', record)
      this.title = '查看角色'
    },
    returnvalue(arr) {
      return arr.map((item) => {
        return item.value
      })
    },
    edit(record) {
      this.mdl = Object.assign({}, record)
      this.visible = true
      console.log('数据', this.mdl)
      this.title = '编辑服务详情绑定'
      this.xsFlag = true
      this.typed = record.type
      // if (record.flImage) {
      //   this.fileList = []
      //   this.fileList.push(JSON.parse(record.flImage))
      // } else {
      //   this.fileList = []
      // }
      this.$nextTick(() => {
        // this.form.setFieldsValue(pick(this.mdl, 'id', 'name', 'code', 'status'))
        this.form.setFieldsValue({
          // id: this.mdl.id,
          // code: this.mdl.name,
          // status: this.mdl.status,
          // name: this.mdl.code,
          id: this.mdl.id,
          serviceid: this.mdl.service.id,
          detailid: this.mdl.detailid.id
        })
      })
      // console.log('this.mdl', this.mdl)
    },
    close() {
      // this.$emit('close')

      this.visible = false
    },
    handleOk() {
      // // 触发表单验证
      // console.log('出发')

      this.form.validateFields((err, values) => {
        // console.log('err', err)

        // 验证表单没错误
        if (!err) {
          console.log('form values', values)
          // const aa = this.filterByValue(this.RolesLists, values.roles)
          // console.log('j橘角色', aa)
          if (values.id > 0) {
            const tabledate = this.$removeSpacesFromObject(values)
            console.log('修改头像', this.fileList)
            console.log('用户的相关信息', tabledate)
            this.$http
              .put('/serviceServicedetail/update', {
                ...tabledate
              })
              .then((res) => {
                console.log('res', res)
                if (res.code === 200) {
                  this.$message.success('修改成功')
                  this.$emit('ok')
                }
              })
          } else {
            const tabledate = this.$removeSpacesFromObject(values)
            // console.log('添加头像', this.fileList)

            console.log('用户的相关信息', tabledate)
            this.$http
              .post('/serviceServicedetail/insert', {
                ...tabledate
              })
              .then((res) => {
                console.log('res', res)
                if (res.code === 200) {
                  this.$message.success('添加成功')
                  this.$emit('ok')
                } else {
                  this.$message.error(res.message)
                }
              })
          }
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onChangeCheck(permission) {
      permission.indeterminate =
        !!permission.selected.length && permission.selected.length < permission.actionsOptions.length
      permission.checkedAll = permission.selected.length === permission.actionsOptions.length
    },
    onChangeCheckAll(e, permission) {
      Object.assign(permission, {
        selected: e.target.checked ? permission.actionsOptions.map((obj) => obj.value) : [],
        indeterminate: false,
        checkedAll: e.target.checked
      })
    },
    del(e) {
      console.log('删除', e)
    },
    disable() {},
    loadPermissions() {
      // const that = this
      // console.log(that)
      this.$http
        .get('/serviceClassification/serviceChild')
        .then((res) => {
          // console.log('下拉权限', res)
          if (res.code === 200) {
            this.RolesLists = res.result
            // console.log('数据', this.RolesLists)
          }
        })
        .catch((err) => {
          console.log('出错', err)
        })
    },
    loadPermissions2() {
      // const that = this
      // console.log(that)
      this.$http
        .get('/servicedetails/serviceChild')
        .then((res) => {
          console.log('下拉权限', res)
          if (res.code === 200) {
            this.RolesLists2 = res.result
            // console.log('数据', this.RolesLists)
          }
        })
        .catch((err) => {
          console.log('出错', err)
        })
    }
  }
}
</script>

<style scoped></style>
